// Copyright 2023 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef VMI_TIMER_H
#define VMI_TIMER_H

#include "VmiThread.h"
#include <ctime>
#include <vector>

const int THREAD_STATUS_EXIT_SLEEP_INTERVAL_MS = 10;        // in milliseconds
const int THREAD_STATUS_NONEXIT_SLEEP_INTERVAL_MS = 10000;  // in milliseconds
const int SECOND_UNIT_MS = 1000;                            // in milliseconds


class VmiTimer {
public:
    unsigned int m_interval;    // ms
    struct timeval m_lastTime = {0, 0};  // ms
    unsigned int m_timerId;     // ms
    explicit VmiTimer(unsigned int interval);

    virtual ~VmiTimer() {}
    virtual void TimeOutCallback() = 0;
    virtual void Reset();
    void SetTimerId(unsigned int timeid);
};

class VmiTimerManage {
public:
    std::vector<VmiTimer *> m_timeVec;
    unsigned int m_tcount;
    static VmiTimerManage* g_instance;
    static VmiTimerManage* GetInstance();
    static void CloseInstance();
    pthread_mutex_t m_lock = {};

    VmiTimerManage();
    ~VmiTimerManage();

    void DeleteAll();
    void AddTimer(VmiTimer* timer);
    void DeleteTimer(VmiTimer* timer);

    void Loop();
};

class VmiTimerThread : public VmiThread {
public:
    VmiTimerThread();
    ~VmiTimerThread() override;
    void Run() override;
};

#endif /* _VMI_TIMER_H_ */
